package cn.collin.commons.web.servlet;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 显示图片
 * 
 * @author collin.code@gmail.com
 * 
 */
public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public static final String fileDir = "z:\\";

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("fileName");
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ServletOutputStream outStream;
		try {
			outStream = response.getOutputStream();

			BufferedImage bufImg = ImageIO.read(new File(fileDir
					+ System.getProperty("file.separator") + fileName));
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);

			encoder.encode(bufImg);

			outStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
